package com.maxima.attendance.actions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import com.maxima.attendance.constants.Constants;
import com.maxima.attendance.daos.TimeLogDAO;
import com.maxima.attendance.pojos.Project;
import com.opensymphony.xwork2.ActionSupport;

public class WorkFromHomeAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private TimeLogDAO timeLogDAO = new TimeLogDAO();
	private List<Project> projectList;
	private String value[];
	private Object strDate;
	// for logging
	static Logger logger = Logger.getLogger(ProjectAction.class.getName());

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	@Action(value = "addWorkFromHome", results = {
		@Result(type = "tiles", location = "showWorkFromHome.tiles")
	}, interceptorRefs = {
		@InterceptorRef(value = "adminStack")
	})
	public String workFromHome() {
		initWorkFromHome();
		return SUCCESS;
	}

	private void initWorkFromHome() {
		setValue(ServletActionContext.getRequest().getParameterValues("duallistbox_demo1[]"));
		setStrDate(ServletActionContext.getRequest().getSession().getAttribute(Constants.SELECTED_DATE));
		timeLogDAO.setWorkFromHome(initList(), true, getDate());
		setProjectList(new InitializeList().initProjectList());
		logger.info("Work from home info. updated successfully [" + initList() + "]");
	}

	private List<Integer> initList() {
		List<Integer> lst = new ArrayList<Integer>();
		if (getValue() != null) {
			for (String string : getValue()) {
				lst.add(Integer.parseInt(string));
			}
		}
		return lst;
	}

	private Date getDate() {
		Date date = null;
		if (getStrDate() != null) {
			try {
				date = new SimpleDateFormat("dd/MM/yyyy").parse(getStrDate().toString());
			}
			catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return date;
	}

	public List<Project> getProjectList() {
		return projectList;
	}

	public void setProjectList(List<Project> projectList) {
		this.projectList = projectList;
	}

	public String[] getValue() {
		return value;
	}

	public void setValue(String[] value) {
		this.value = value;
	}

	public Object getStrDate() {
		return strDate;
	}

	public void setStrDate(Object strDate) {
		this.strDate = strDate;
	}
}